<?php


namespace app\api\controller\Warehouse;

use app\api\model\Warehouse;
use app\api\model\Warehouse\Store as StoreModel;
use app\api\controller\Common;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\facade\Request;

class WarehouseStore extends Common
{
    /**
     * @param StoreModel $store
     * @param Request $request
     * @return \think\response\Json
     */
    public function index(StoreModel $store, Request $request)
    {
        try {
            return $this->returnJson(200, 'ok', $store->page(
                $request::param('page', 20),
                $request::param('size', 10)
            )->paginate($request::param('size', 10)));
        } catch (DbException $e) {
            return $this->returnJson(500, $e->getMessage());
        }
    }

    /**
     * @param $id
     * @param StoreModel $store
     * @param Request $request
     * @return \think\response\Json
     */
    public function indexWarehouse($id, StoreModel $store, Request $request)
    {
        try {
            return $this->returnJson(200, 'ok', Db::name('warehouse')->where('store', $store::get($id)->id)->page(
                $request::param('page', 20),
                $request::param('size', 10)
            )->paginate($request::param('size', 10)));
        } catch (DbException $e) {
            return $this->returnJson(500, $e->getMessage());
        }
    }

    /**
     * @param $id
     * @param StoreModel $store
     * @return \think\response\Json
     */
    public function read($id, StoreModel $store)
    {
        try {
            return $this->returnJson(200, 'ok', $store->findOrFail($id));
        } catch (DataNotFoundException $e) {
            return $this->returnJson(404, $e->getMessage());
        } catch (ModelNotFoundException $e) {
            return $this->returnJson(404, $e->getMessage());
        } catch (DbException $e) {
            return $this->returnJson(500, $e->getMessage());
        }
    }

    /**
     * @param Request $request
     * @param StoreModel $store
     * @return StoreModel
     */
    public function save(Request $request, StoreModel $store)
    {
        return $this->returnJson(200, 'ok', $store::create($request::param(), ['name']));
    }

    /**
     * @param $id
     * @param StoreModel $store
     * @param Request $request
     * @return StoreModel
     */
    public function update($id, StoreModel $store, Request $request)
    {
        return $store::update($request::param(), ['id' => $id]);
    }

    /**
     * @param $id
     * @param StoreModel $store
     * @return bool
     */
    public function delete($id, StoreModel $store)
    {
        return $this->returnJson(200, 'ok', $store::destroy($id));
    }
}
